//
//  LKRefreshControll.swift
//  新浪微博
//
//  Created by 胡不归是大虾 on 16/9/29.
//  Copyright © 2016年 胡不归是大虾. All rights reserved.
//

import UIKit
private let refreshHeight: CGFloat = 50
//定义三种状态枚举值
enum RefreshStatus: Int {
    case Default = 0
    case isPulling
    case isRefreshing
}

class LKRefreshControll: UIControl {

    //重写构造方法,设置frame
    override init(frame: CGRect) {
        let rect = CGRect(x: 0, y: -refreshHeight, width: ScreenWidth, height: refreshHeight)
        super.init(frame: rect)
//        self.backgroundColor = UIColor.orange
        setUpUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    //监听scrollView的contentOffset
    override func willMove(toSuperview newSuperview: UIView?) {
        super.willMove(toSuperview: newSuperview)
        //判断如果是scrollView或者是其子类,就监听contentOffset
        if let scrollView = newSuperview as? UIScrollView {
            //赋值
            self.scrollView = scrollView
            //添加观察对象,实现监听方法,移除监听者
            scrollView.addObserver(self, forKeyPath: "contentOffset", options: .new, context: nil)
        }
    }
    //实现监听方法
    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        //临界值和当前值做判断
        let markOffset: CGFloat = -114
        let currentOffset = self.scrollView?.contentOffset.y ?? 0
        if scrollView!.isDragging {
            //正在拖动
            if refreshStatus == .Default && currentOffset < markOffset {
                refreshStatus = .isPulling
            }
            else if refreshStatus == .isPulling &&  currentOffset > markOffset{
                refreshStatus = .Default
            }}
            else
            {
                if refreshStatus == .isPulling {
                    refreshStatus = .isRefreshing
                }
            }
        
    }
    //MARK:设置子控件约束
    private func setUpUI () {
        addSubview(tipLabel)
        addSubview(indicatorView)
        addSubview(arrowIcon)
        tipLabel.snp.makeConstraints { (make) in
            make.centerX.equalTo(self).offset(10)
            make.centerY.equalTo(self)
        }
        arrowIcon.snp.makeConstraints { (make) in
            make.centerY.equalToSuperview()
            make.right.equalTo(tipLabel.snp.left).offset(-5)
        }
        indicatorView.snp.makeConstraints { (make) in
            make.center.equalTo(arrowIcon)
        }
    }
    //MARK:懒加载子控件
    //声明一个scrollView属性,方便移除监听者
    var refreshStatus: RefreshStatus = .Default {
        didSet{
            switch refreshStatus {
            case .Default:
                arrowIcon.isHidden = false
                tipLabel.text = "下拉刷新"
                indicatorView.stopAnimating()
                if oldValue == .isRefreshing {
                    UIView.animate(withDuration: 0.5, animations: { 
                        self.scrollView!.contentInset.top = self.scrollView!.contentInset.top - refreshHeight
                    })
                }
                //变换箭头的形态
                UIView.animate(withDuration: 0.25, animations: { 
                    self.arrowIcon.transform = CGAffineTransform.identity
                })
            case .isPulling:
                arrowIcon.isHidden = false
                tipLabel.text = "松手刷新"
                indicatorView.stopAnimating()
                UIView.animate(withDuration: 0.25, animations: { 
                    self.arrowIcon.transform = CGAffineTransform.init(rotationAngle: CGFloat(M_PI))
                })
            case .isRefreshing:
                arrowIcon.isHidden = true
                indicatorView.startAnimating()
                tipLabel.text = "正在刷新"
                scrollView!.contentInset.top = scrollView!.contentInset.top + refreshHeight
                self.sendActions(for: .valueChanged)
            }
        }
    }
    func stopAnimating(){
        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.5) { 
            self.refreshStatus = .Default
        }
    }
    var scrollView: UIScrollView?
    lazy var tipLabel : UILabel = UILabel(title: "下拉刷新", font: 14, textColor: UIColor.gray)
    lazy var arrowIcon : UIImageView = UIImageView(image:#imageLiteral(resourceName: "tableview_pull_refresh"))
    lazy var indicatorView : UIActivityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: .gray)
    //移除监听者
    deinit {
        self.scrollView?.removeObserver(self, forKeyPath: "contentOffset")
    }
}
